<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/1/5
 * Time: 11:21
 */

namespace iBrand\Shop\Server\Http\Controllers;

use Carbon\Carbon;
use iBrand\Component\Order\Models\OrderItem;
use iBrand\Component\Order\Processor\OrderProcessor;
use iBrand\Component\Product\Models\Goods;
use iBrand\Component\Product\Models\Product;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Order;
use iBrand\Shop\Core\Models\Refund;
use iBrand\Shop\Core\Models\RefundItem;
use iBrand\Shop\Core\Models\ShopOrder;
use iBrand\Shop\Core\Repositories\OrderRepository;
use iBrand\Shop\Server\Transformers\OrderItemTransformer;
use iBrand\Shop\Server\Transformers\RefundTransformer;
use DB;

class RefundController extends Controller
{
    protected $orderRepository;
    protected $orderProcessor;

    public function __construct(OrderRepository $orderRepository
        , OrderProcessor $orderProcessor)
    {
        $this->orderRepository = $orderRepository;
        $this->orderProcessor = $orderProcessor;
    }

    /**
     * 申请售后基础信息
     *
     * @return \Dingo\Api\Http\Response|void
     */
    public function baseInfo()
    {
        $item_id = request('order_item_id');
        if (!$item_id OR !$orderItem = OrderItem::find($item_id)) {
            return $this->response()->errorBadRequest('订单商品不存在');
        }

        return $this->response()->item($orderItem, new OrderItemTransformer());
    }

    /**
     * 提交退货申请
     *
     * @return \Dingo\Api\Http\Response|void
     */
    public function applyReturn()
    {
        $clerk = auth('clerk')->user();
        $order_id = request('order_id');
        if (!$order_id || !$order = $this->orderRepository->find($order_id)) {

            return $this->api([], false, 500, '订单不存在');
        }

        if (!$order->shopOrder) {
            return $this->api([], false, 500, '订单不存在');
        }

        if (!$orderItem = OrderItem::find(request('order_item_id'))) {

            return $this->api([], false, 500, '订单不存在');
        }

        if (!request('quantity') OR $orderItem->quantity < request('quantity')) {

            return $this->api([], false, 500, '提交数量错误');
        }

        if ($clerk->shops->shop_id != $order->shopOrder->shop_id) {

            return $this->api([], false, 500, '无权限提交');
        }

        if (Refund::where('order_item_id', request('order_item_id'))->first()) {

            return $this->api([], false, 500, '您已提交过售后');
        }

        $input = array_filter(request()->only('order_item_id', 'images', 'type', 'quantity',
            'content', 'reason', 'amount'));

        if ($amount = request('amount') * 100) {
            if ($orderItem->quantity <> $input['quantity']) {
                $theory = ($orderItem->total / $orderItem->quantity) * $input['quantity'];
                $temp = $amount;

                if ($theory < $temp) {
                    return $this->response()->errorForbidden('提交退款金额错误');
                }
            } else {
                if ($orderItem->total < $amount) {
                    return $this->response()->errorForbidden('提交退款金额错误');
                }
            }
            $input['amount'] = $amount;
        } else {
            $input['amount'] = ($orderItem->total / $orderItem->quantity) * $input['quantity'];
        }

        try {
            DB::beginTransaction();

            //1.生成创建需要的参数
            $input = array_merge(['user_id' => $order->user_id, 'order_id' => $order->id], $input);
            $input['type'] = 4;
            $input['channel'] = 'shop';
            $input['channel_id'] = $clerk->shop_id;

            $refund = new Refund($input);
            $refund->save();

            $guide = $clerk->name;
            $note = '导购员' . $guide . '为用户提交退货申请';
            RefundItem::create(['refund_id' => $refund->id, 'user_id' => $order->user_id, 'action' => 'create', 'note' => $note]);

            DB::commit();

            return $this->api(['refund' => $refund]);
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());
            $this->response()->errorInternal($exception->getMessage());
        }
    }

    /**
     * 提交换货申请
     *
     * @return \Dingo\Api\Http\Response|void
     */
    public function applyExchange()
    {
        $clerk = auth('clerk')->user();

        $difference_amount = request('difference_amount') * 100;    //差价
        $need_pay = true;

        $order_id = request('order_id');
        if (!$order_id || !$order = $this->orderRepository->find($order_id)) {

            return $this->api([], false, 500, '订单不存在');
        }

        if (!$order->shopOrder) {

            return $this->api([], false, 500, '订单不存在');
        }

        if (!$orderItem = OrderItem::find(request('order_item_id'))) {

            return $this->api([], false, 500, '订单不存在');
        }

        if (!request('quantity') OR $orderItem->quantity < request('quantity')) {

            return $this->api([], false, 500, '提交数量错误');
        }

        if ($clerk->shops->shop_id != $order->shopOrder->shop_id) {

            return $this->api([], false, 500, '无权限提交');
        }

        if (Refund::where('order_item_id', request('order_item_id'))->first()) {

            return $this->api([], false, 500, '您已提交过售后');
        }

        //TODO: 已经提交过的不能再次提交

        $input = array_filter(request()->only('order_item_id', 'images', 'type', 'quantity',
            'content', 'reason'));

        if ($orderItem->quantity < $input['quantity']) {

            return $this->api([], false, 500, '提交换货数量错误');
        }

        try {
            DB::beginTransaction();
            //1.生成创建需要的参数
            $input = array_merge(['user_id' => $order->user_id, 'order_id' => $order->id], $input);
            $input['type'] = 2;
            $input['amount'] = ($orderItem->total / $orderItem->quantity) * $input['quantity'];
            $input['channel'] = 'shop';
            $input['channel_id'] = $clerk->shop_id;

            $refund = new Refund($input);
            $refund->save();

            $guide = $clerk->name;
            $note = '导购员' . $guide . '为用户提交换货申请';
            RefundItem::create(['refund_id' => $refund->id, 'user_id' => $order->user_id, 'action' => 'create', 'note' => $note]);

            //create order
            $order = new Order([
                'user_id' => $order->user_id,
                'type' => Order::TYPE_SHOP,
                'address_name' => '现场提货',
                'submit_time' => Carbon::now(),
                'channel' => 'shop',
                'channel_id' => $clerk->shop_id
            ]);
            $order->order_no = build_order_no('ST');
            $order->status = Order::STATUS_NEW;

            $exchangeData = request('exchangeData');

            foreach ($exchangeData as $item) {
                if ($item['qty'] > 0) {
                    if (isset($item['product_id']) AND isset($item['sku'])) {
                        $product = Product::find($item['product_id']);
                        $type = 'iBrand\Component\Product\Models\Product';
                        $detail_id = $product->goods_id;
                    } else {
                        $product = Goods::find($item['goods_id']);
                        $type = 'iBrand\Component\Product\Models\Goods';
                        $detail_id = $item['goods_id'];
                    }

                    if(!$product){
                        return $this->api([], false, 500, '商品不存在');
                    }

                    if (!$product->getO2oProduct($clerk->shop_id)->getIsInSale($item['qty'])) {

                        return $this->api([], false, 500, '商品库存不够，请重新下单');
                    }

                    $item_meta = [
                        'image' => $item['image'],
                        'detail_id' => $detail_id,
                        'spec_text' => $product->spec_text,
                    ];
                    $orderItem = new OrderItem([
                        'quantity' => $item['qty'],
                        'unit_price' => $product->sell_price,
                        'item_id' => $item['product_id'],
                        'type' => $type,
                        'item_name' => $item['name'],
                        'item_meta' => $item_meta,
                    ]);
                    $orderItem->recalculateUnitsTotal();

                    $order->addItem($orderItem);
                }
            }

            if ($order->total - $input['amount'] <> $difference_amount) {
                $difference_amount = $order->total - $input['amount'];
            }

            if ($difference_amount <= 0) {
                $need_pay = false;

                $order->status = Order::STATUS_COMPLETE;
                $order->pay_time = Carbon::now();
                $order->completion_time = Carbon::now();
                $order->pay_status = 1;
                $order->distribution_status = 1;
            }

            \Log::info([$order]);
            \Log::info($order->toArray());
            if (!$order = $this->orderProcessor->create($order)) {

                return $this->api([], false, 500, '提交失败，请确认后重试');
            }

            if (!ShopOrder::where('order_id', $order->id)->first()) {
                $ratio = settings('o2o_clerk_royalty_ratio') ? settings('o2o_clerk_royalty_ratio') / 100 : 0;
                $value = $order->total * $ratio;
                ShopOrder::create(['order_id' => $order->id, 'clerk_id' => $clerk->id, 'shop_id' => $clerk->shop_id, 'value' => $value]);
            };

            //create order refund relation
            $refund->orderRefund()->create([
                'order_id' => $order->id,
                'refund_amount' => $input['amount'],
                'difference_amount' => $difference_amount,
            ]);

            DB::commit();

            return $this->api(['refund' => $refund, 'order' => $order, 'need_pay' => $need_pay]);
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());

            return $this->api([], false, 500, '提交失败，请确认后重试');
        }
    }

    /**
     * 完成售后
     *
     * @return \Dingo\Api\Http\Response
     */
    public function refundProcessor()
    {
        if (!$refund = Refund::where('refund_no', request('refund_no'))->get()->first()) {
            return $this->api(null, false, 400, '不存在该售后申请');
        }

        if ($refund->status == Refund::STATUS_AUDIT) {
            $refund->status = Refund::STATUS_COMPLETE;
            $refund->paid_time = Carbon::now();
            $refund->save();

            event('shop.refund.completed', [$refund]);
        }

        return $this->api($refund);
    }

    /**
     * 查看售后详情
     *
     * @param $refund_no
     *
     * @return \Dingo\Api\Http\Response
     */
    public function show($refund_no)
    {
        $clerk = auth('clerk')->user();
        if (!$refund = Refund::where('refund_no', $refund_no)->with('orderItem')->get()->first()) {
            return $this->api(null, false, 400, '不存在该售后申请');
        }

        if ($clerk->shop_id != $refund->order->shopOrder->shop_id) {
            return $this->api(null, false, 400, '无权限查看该售后');
        }

        return $this->response()->item($refund, new RefundTransformer());
    }
}